#!/usr/bin/env node

const { chromium } = require('playwright');
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');

let context = null;
let page = null;
let userDataDir = path.join(__dirname, 'browser-data');
let server = null;
let port = 3001; // 默认端口

async function initialize() {
    if (!context) {
        console.log('初始化Playwright浏览器...');
        
        try {
            // 使用固定的用户数据目录
            context = await chromium.launchPersistentContext(userDataDir, {
                headless: false,
                args: [
                    '--no-sandbox',
                    '--disable-dev-shm-usage',
                    '--disable-gpu',
                    '--disable-extensions',
                    '--disable-infobars',
                    '--start-maximized',
                    '--ignore-certificate-errors',
                    '--ignore-ssl-errors'
                ],
                viewport: null,
                userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
            });
            
            // 获取第一个页面，如果没有则创建新页面
            const pages = context.pages();
            if (pages.length > 0) {
                page = pages[0];
                console.log('使用现有页面');
            } else {
                page = await context.newPage();
                console.log('创建新页面');
            }
            
            console.log('浏览器初始化完成');
        } catch (error) {
            console.error('浏览器初始化失败:', error.message);
            throw error;
        }
    }
}

async function openLoginPage() {
    await initialize();
    console.log('打开小红书登录页面...');

    try {
        await page.goto('https://creator.xiaohongshu.com/login', {
            waitUntil: 'networkidle',
            timeout: 30000
        });

        console.log('登录页面已打开，请手动完成登录...');
        return { success: true, message: '登录页面已打开，请手动完成登录' };
    } catch (error) {
        console.error('打开登录页面失败:', error.message);
        return { success: false, error: error.message };
    }
}

async function checkLoginStatus() {
    await initialize();
    console.log('检查登录状态...');

    try {
        // 等待页面加载
        await page.waitForLoadState('networkidle', { timeout: 10000 });

        let currentUrl = page.url();
        console.log(`当前URL: ${currentUrl}`);

        // 如果页面是空白，先导航到小红书
        if (currentUrl === 'about:blank' || currentUrl === '') {
            console.log('页面为空白，导航到小红书...');
            await page.goto('https://creator.xiaohongshu.com', {
                waitUntil: 'networkidle',
                timeout: 30000
            });
            currentUrl = page.url();
            console.log(`导航后URL: ${currentUrl}`);
        }

        // 检查是否在登录页面
        const isOnLoginPage = currentUrl.includes('login') || currentUrl.includes('creator.xiaohongshu.com/login');
        
        if (isOnLoginPage) {
            console.log('仍在登录页面，未登录');
            return { isLoggedIn: false, message: '仍在登录页面，未登录' };
        }

        // 检查是否在创作者中心页面
        const isOnCreatorPage = currentUrl.includes('creator.xiaohongshu.com') && 
                               !currentUrl.includes('login') && 
                               (currentUrl.includes('creator') || currentUrl.includes('dashboard') || currentUrl.includes('publish') || currentUrl.includes('new/home'));

        if (isOnCreatorPage) {
            console.log('已登录，在创作者中心页面');
            return { isLoggedIn: true, message: '已登录，在创作者中心页面' };
        }

        // 检查页面内容
        const pageContent = await page.content();
        console.log('页面内容长度:', pageContent.length);
        
        // 检查是否有登录相关元素
        const hasLoginElements = pageContent.includes('login') || 
                               pageContent.includes('登录') || 
                               pageContent.includes('手机号') ||
                               pageContent.includes('验证码');
        
        // 检查是否有创作者中心元素
        const hasCreatorElements = pageContent.includes('创作者') || 
                                 pageContent.includes('发布') || 
                                 pageContent.includes('数据') ||
                                 pageContent.includes('dashboard') ||
                                 pageContent.includes('publish') ||
                                 pageContent.includes('new/home') ||
                                 pageContent.includes('笔记管理') ||
                                 pageContent.includes('数据看板');

        console.log('包含登录元素:', hasLoginElements);
        console.log('包含创作者元素:', hasCreatorElements);

        if (hasCreatorElements && !hasLoginElements) {
            console.log('已登录，检测到创作者中心元素');
            return { isLoggedIn: true, message: '已登录，检测到创作者中心元素' };
        }

        if (hasLoginElements) {
            console.log('未登录，检测到登录元素');
            return { isLoggedIn: false, message: '未登录，检测到登录元素' };
        }

        console.log('登录状态不明确，URL:', currentUrl);
        return { isLoggedIn: false, message: '登录状态不明确' };

    } catch (error) {
        console.error('检查登录状态时出错:', error.message);
        return { isLoggedIn: false, error: error.message };
    }
}

async function getLoginInfo() {
    await initialize();
    console.log('获取登录信息...');

    try {
        const statusResult = await checkLoginStatus();

        if (!statusResult.isLoggedIn) {
            return {
                success: false,
                message: '用户未登录'
            };
        }

        const cookies = await context.cookies();

        let userInfo = null;
        try {
            // 尝试多种方式获取用户信息
            const userInfoSelectors = [
                '[data-testid="user-info"]',
                '.user-info',
                '.avatar',
                '.username',
                '.nickname',
                '[class*="user"]',
                '[class*="nickname"]',
                '.profile-name',
                '.user-name'
            ];
            
            for (const selector of userInfoSelectors) {
                const element = await page.$(selector);
                if (element) {
                    userInfo = await element.textContent();
                    if (userInfo && userInfo.trim()) {
                        console.log('找到用户信息:', userInfo);
                        break;
                    }
                }
            }
        } catch (e) {
            console.log('无法获取用户信息:', e.message);
        }

        const title = await page.title();
        const currentUrl = page.url();

        const loginInfo = {
            success: true,
            message: '登录成功',
            cookies: cookies,
            userInfo: userInfo,
            title: title,
            url: currentUrl
        };

        console.log('登录信息获取成功');
        return loginInfo;

    } catch (error) {
        console.error('获取登录信息时出错:', error.message);
        return {
            success: false,
            message: `获取登录信息失败: ${error.message}`
        };
    }
}

async function close() {
    console.log('关闭浏览器');
    if (context) {
        await context.close();
    }
    context = null;
    page = null;
}

// HTTP服务器
function createServer() {
    server = http.createServer(async (req, res) => {
        // 设置CORS头
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
        res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
        
        // 处理OPTIONS请求
        if (req.method === 'OPTIONS') {
            res.writeHead(200);
            res.end();
            return;
        }

        const parsedUrl = url.parse(req.url, true);
        const pathname = parsedUrl.pathname;

        try {
            let result;
            
            switch (pathname) {
                case '/open-login':
                    result = await openLoginPage();
                    break;
                    
                case '/check-status':
                    result = await checkLoginStatus();
                    break;
                    
                case '/get-info':
                    result = await getLoginInfo();
                    break;
                    
                case '/close':
                    result = { success: true, message: '关闭命令已发送' };
                    // 延迟关闭，让响应先发送
                    setTimeout(() => {
                        close().then(() => {
                            console.log('浏览器已关闭，服务器即将退出');
                            process.exit(0);
                        });
                    }, 1000);
                    break;
                    
                case '/health':
                    result = { success: true, message: '服务器运行正常' };
                    break;
                    
                default:
                    result = { 
                        success: false, 
                        error: '未知路径',
                        availableEndpoints: [
                            '/open-login - 打开登录页面',
                            '/check-status - 检查登录状态',
                            '/get-info - 获取登录信息',
                            '/close - 关闭浏览器',
                            '/health - 健康检查'
                        ]
                    };
            }

            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify(result, null, 2));
            
        } catch (error) {
            console.error('处理请求时出错:', error);
            res.writeHead(500, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ 
                success: false, 
                error: error.message 
            }, null, 2));
        }
    });

    server.listen(port, () => {
        console.log(`浏览器服务器启动在端口 ${port}`);
        console.log('可用接口:');
        console.log(`  GET http://localhost:${port}/open-login - 打开登录页面`);
        console.log(`  GET http://localhost:${port}/check-status - 检查登录状态`);
        console.log(`  GET http://localhost:${port}/get-info - 获取登录信息`);
        console.log(`  GET http://localhost:${port}/close - 关闭浏览器`);
        console.log(`  GET http://localhost:${port}/health - 健康检查`);
    });

    return server;
}

// 处理进程退出
process.on('SIGINT', async () => {
    console.log('收到中断信号，正在关闭服务器...');
    if (server) {
        server.close();
    }
    await close();
    process.exit(0);
});

process.on('SIGTERM', async () => {
    console.log('收到终止信号，正在关闭服务器...');
    if (server) {
        server.close();
    }
    await close();
    process.exit(0);
});

// 启动服务器
if (require.main === module) {
    createServer();
}

module.exports = { createServer, openLoginPage, checkLoginStatus, getLoginInfo, close }; 